package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.YanShouDaiBean;
import com.wnhz.work.yz.bean.YanShouDaiDetailsBean;
import com.wnhz.work.yz.sql.DBHelper;
import com.wnhz.work.yz.utils.GlideImageLoader;
import com.wnhz.work.yz.utils.MyUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YanShouDaiActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recycler;
    private LinearLayout status1, status2;
    private View line1, line2;
    private DBHelper sql;
    private SQLiteDatabase db;
    private TextView submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yan_shou_dai);
        //todo 创建数据库表
        //  initDb();

        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("验收项目");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
//        LinearLayout ll_search = (LinearLayout) findViewById(R.id.ll_search);
//        ll_search.setVisibility(View.VISIBLE);
//        ll_search.setOnClickListener(this);
        submit = (TextView) findViewById(R.id.submit);
        submit.setText("分配");
        submit.setVisibility(View.VISIBLE);
        findViewById(R.id.submit).setOnClickListener(this);
        status1 = (LinearLayout) findViewById(R.id.status1);
        status2 = (LinearLayout) findViewById(R.id.status2);
        status1.setOnClickListener(this);
        status2.setOnClickListener(this);
        line1 = findViewById(R.id.line1);
        line2 = findViewById(R.id.line2);
        upLoad(0);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private void initDb() {
        sql = new DBHelper(this);
        db = sql.getReadableDatabase();
    }

    private List<YanShouDaiBean.InfoEntity> info1 = new ArrayList<>();

    private void upLoad(final int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("keywords", "");
        map.put("type", type);

        showDialog();
        XUtil.Post(Url.DECORATE_WAITIMGCHECKLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        YanShouDaiBean bean = gson.fromJson(result, YanShouDaiBean.class);
                        info1 = bean.getInfo();
                        initRecycler(recycler, info1, type);
                        recycler.setVisibility(View.VISIBLE);
                        //// TODO: 2017/6/19 给第二个表添加数据
                        // initDaData(info1);

                    } else {
                        recycler.setVisibility(View.GONE);
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });


    }

    private BaseRVAdapter adapter;

    private void initRecycler(RecyclerView recycler, final List<YanShouDaiBean.InfoEntity> info, final int type) {
        adapter = new BaseRVAdapter(this, info) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_yanshou_dai;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {

                if ("1".equals(info.get(position).getIs_tranfer())) {
                    holder.getView(R.id.ll_select).setVisibility(View.GONE);
                    holder.getView(R.id.fenpei).setVisibility(View.VISIBLE);
                    holder.setTextView(R.id.elsetime, info.get(position).getTranfer_time());
                    holder.getView(R.id.istrue).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            doWhat(position, info.get(position).getOrderid(), 1);
                        }
                    });
                    holder.getView(R.id.isfalse).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            doWhat(position, info.get(position).getOrderid(), 2);

                        }
                    });


                } else {
                    holder.getView(R.id.fenpei).setVisibility(View.GONE);
                    if (info.get(position).getOpen() == 1) {
                        holder.getView(R.id.ll_select).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.ll_select).setVisibility(View.GONE);
                    }

                    if (info.get(position).getSelect() == 1) {
                        holder.getImageView(R.id.select).setImageResource(R.mipmap.ic_choose_li);
                    } else {
                        holder.getImageView(R.id.select).setImageResource(R.mipmap.ic_choose_nor);
                    }
                    holder.getView(R.id.ll_select).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            info.get(position).setSelect(info.get(position).getSelect() == 1 ? 0 : 1);
                            notifyDataSetChanged();
                        }
                    });
                }


                if (info.get(position).getImg() != null && info.get(position).getImg().size() > 0) {
                    Banner img = holder.getView(R.id.img2);
                    img.setImageLoader(new GlideImageLoader());
                    //设置图片集合
                    img.setImages(info.get(position).getImg());
                    img.setBannerStyle(BannerConfig.NOT_INDICATOR);
                    //banner设置方法全部调用完毕时最后调用
                    img.start();
                }

                holder.getTextView(R.id.name).setText(info.get(position).getProject_name());
                holder.getTextView(R.id.hetonghao).setText("" + info.get(position).getBudget_no());
                holder.getTextView(R.id.time).setText("" + info.get(position).getCheck_time());
                holder.getTextView(R.id.address).setText("" + info.get(position).getAddress());
                holder.getTextView(R.id.anzhuang).setText("安装队：" + info.get(position).getInstall());
                if (type == 0) {
                    holder.getTextView(R.id.or).setText("总套数：" + info.get(position).getAll_nums() + "套/已报检套数：" + info.get(position).getHas_nums() + "套");
                } else {
                    holder.getTextView(R.id.or).setText("总套数：" + info.get(position).getAll_nums() + "套/未报检套数：" + info.get(position).getHas_nums() + "套");
                }
                holder.getView(R.id.ll_max).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getDetails(position);
                    }
                });

            }


        };
        recycler.setAdapter(adapter);

    }

    private void doWhat(final int position, String orderid, final int i) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", orderid);
        map.put("status", i);
        showDialog();

        XUtil.Post(Url.DECORATE_DOWHATTOORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        MyToast(info);
                        if (i == 1) {
                            info1.get(position).setIs_tranfer("0");
                            adapter.notifyDataSetChanged();
                        } else {
                            info1.remove(position);
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });

    }


    private void initDaData(List<YanShouDaiBean.InfoEntity> info1) {
        Cursor cursor = db.rawQuery("select * from project ", null);
        String a[] = new String[info1.size()];
        int n = 0;
        List<String> bb = new ArrayList<>();
        while (cursor.moveToNext()) {
            bb.add(cursor.getString(cursor.getColumnIndex("orderid")));
            n++;
        }
        //如果数据库存在一些数据，就添加不存在的新增的数据，否则全部添加
        Log.e("---project数据库num", "---" + n);
        if (n > 0) {
            for (int i = 0; i < a.length; i++) {
                a[i] = info1.get(i).getOrderid();
            }
            List<YanShouDaiBean.InfoEntity> info3 = new ArrayList<>();
            String b[] = new String[bb.size()];
            for (int i = 0; i < b.length; i++) {
                b[i] = bb.get(i);
            }
            String[] minus = MyUtils.minus(a, b);

            for (int i = 0; i < info1.size(); i++) {
                for (int j = 0; j < minus.length; j++) {
                    if (minus[j].equals(info1.get(i).getOrderid())) {
                        info3.add(info1.get(i));
                    }
                }
            }
            for (int i = 0; i < info3.size(); i++) {
                String imgs = "";
                for (int j = 0; j < info3.get(i).getImg().size(); j++) {
                    imgs += "" + info3.get(i).getImg().get(j);
                    if (j != info3.get(i).getImg().size() - 1) {
                        imgs += ",";
                    }
                }
                db.execSQL("insert into project(orderid,address,install,check_time,all_nums," +
                        "has_nums,project_name,budget_no,img) values(\"" +
                        info3.get(i).getOrderid() + "\",\"" +
                        info3.get(i).getAddress() + "\",\"" +
                        info3.get(i).getInstall() + "\",\"" +
                        info3.get(i).getCheck_time() + "\",\"" +
                        info3.get(i).getAll_nums() + "\",\"" +
                        info3.get(i).getHas_nums() + "\",\"" +
                        info3.get(i).getProject_name() + "\",\"" +
                        info3.get(i).getBudget_no() + "\",\"" +
                        imgs + "\"  )");
            }
        } else {
            for (int i = 0; i < info1.size(); i++) {
                String imgs = "";
                for (int j = 0; j < info1.get(i).getImg().size(); j++) {
                    imgs += "" + info1.get(i).getImg().get(j);
                    if (j != info1.get(i).getImg().size() - 1) {
                        imgs += ",";
                    }
                }
                db.execSQL("insert into project(orderid,address,install,check_time,all_nums," +
                        "has_nums,project_name,budget_no,img) values(\"" +
                        info1.get(i).getOrderid() + "\",\"" +
                        info1.get(i).getAddress() + "\",\"" +
                        info1.get(i).getInstall() + "\",\"" +
                        info1.get(i).getCheck_time() + "\",\"" +
                        info1.get(i).getAll_nums() + "\",\"" +
                        info1.get(i).getHas_nums() + "\",\"" +
                        info1.get(i).getProject_name() + "\",\"" +
                        info1.get(i).getBudget_no() + "\",\"" +
                        imgs + "\"  )");
            }
        }


    }


    private void getDetails(final int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", info1.get(position).getOrderid());
        showDialog();

        XUtil.Post(Url.DECORATE_WAITINGCHECKDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        YanShouDaiDetailsBean bean = gson.fromJson(result, YanShouDaiDetailsBean.class);
                        startActivity(new Intent(YanShouDaiActivity.this, YanShouDaiChanPinActivity.class).putExtra("bean", bean));
                        //添加关联数据库2，子类数据库
                        //Todo 添加关联数据库2
                        //addDb2(position, bean);


                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });


    }

    private void addDb2(int position, YanShouDaiDetailsBean bean) {
        Cursor cursor = db.rawQuery("select * from product where project_id=\"" + info1.get(position).getOrderid() + "\"", null);

        String a[] = new String[bean.getInfo().size()];
        int n = 0;
        List<String> bb = new ArrayList<>();
        while (cursor.moveToNext()) {
            bb.add(cursor.getString(cursor.getColumnIndex("pid")));
            n++;
        }

        Log.e("---product数据库num", "---" + n);
        if (n > 0) {
            for (int i = 0; i < bean.getInfo().size(); i++) {
                a[i] = bean.getInfo().get(i).getPid();
            }

            String b[] = new String[bb.size()];
            for (int i = 0; i < bb.size(); i++) {
                b[i] = bb.get(i);
            }
            String c[] = MyUtils.minus(a, b);
            List<YanShouDaiDetailsBean.InfoEntity> info = new ArrayList<>();

            for (int i = 0; i < bean.getInfo().size(); i++) {
                for (int j = 0; j < c.length; j++) {
                    if (bean.getInfo().get(i).getPid().equals(c[j])) {
                        info.add(bean.getInfo().get(i));
                    }
                }
            }
            for (int i = 0; i < info.size(); i++) {
                db.execSQL(" insert into product(project_id,status,company,name," +
                        "score,img,number,pid,house,type,info) values(\n" +
                        "    \"" + info1.get(position).getOrderid() + "\",\n" +
                        "    \"" + info.get(i).getStatus() + "\",\n" +
                        "    \"" + info.get(i).getCompany() + "\",\n" +
                        "    \"" + info.get(i).getName() + "\",\n" +
                        "    \"" + info.get(i).getScore() + "\",\n" +
                        "    \"" + info.get(i).getImg() + "\",\n" +
                        "    \"" + info.get(i).getNumber() + "\",\n" +
                        "    \"" + info.get(i).getPid() + "\",\n" +
                        "    \"" + info.get(i).getHouse() + "\",\n" +
                        "    \"" + info.get(i).getType() + "\",\n" +
                        "    \"" + info.get(i).getInfo() + "\"\n" +
                        " )");

            }


        } else {
            for (int i = 0; i < bean.getInfo().size(); i++) {

                db.execSQL(" insert into product(project_id,status,company,name," +
                        "score,img,number,pid,house,type,info) values(\n" +
                        "    \"" + info1.get(position).getOrderid() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getStatus() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getCompany() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getName() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getScore() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getImg() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getNumber() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getPid() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getHouse() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getType() + "\",\n" +
                        "    \"" + bean.getInfo().get(i).getInfo() + "\"\n" +
                        " )");

            }
        }


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

//            case R.id.ll_search:
//                startActivity(new Intent(this, YanShouDaiSearchActivity.class));
//
//                break;
//            分配
            case R.id.submit:
                if ("分配".equals(submit.getText())) {
                    submit.setText("确认");
                    for (int i = 0; i < info1.size(); i++) {
                        info1.get(i).setOpen(1);
                    }
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    StringBuffer sb = new StringBuffer("-");
                    for (int i = 0; i < info1.size(); i++) {
                        if (info1.get(i).getSelect() == 1) {
                            sb.append(info1.get(i).getOrderid() + "-");
                        }
                    }
                    submit.setText("分配");
                    if ("-".equals(sb.toString())) {
                        for (int i = 0; i < info1.size(); i++) {
                            info1.get(i).setOpen(0);
                        }
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }
                        return;
                    }
                    startActivity(new Intent(YanShouDaiActivity.this, YanShouYuanLieBiaoActivity.class).putExtra("orderid", sb.toString()));

                    for (int i = 0; i < info1.size(); i++) {
                        info1.get(i).setOpen(0);
                        info1.get(i).setSelect(0);
                    }
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                }

                break;
            case R.id.status1:
                line1.setVisibility(View.VISIBLE);
                line2.setVisibility(View.GONE);
                submit.setVisibility(View.VISIBLE);
                submit.setText("分配");
                upLoad(0);
                break;
            case R.id.status2:
                submit.setVisibility(View.GONE);
                line2.setVisibility(View.VISIBLE);
                line1.setVisibility(View.GONE);
                upLoad(1);
                break;
        }
    }
}
